/**
 * @description 搜索
 */
import style from './styles/App.less';
import classnames from "classnames";
import React from 'react';
import EntryBase from "../Common/EntryBase";
const Fragment = React.Fragment;
import { Button, Toast } from 'wd-mobile';
import CategoryGoodsItem from "components/CategoryGoodsItem";
import ScrollReachEndContainer from "components/ScrollReachEndContainer";

import icon_search from "images/icon/search.png";
import img_empty from "./images/empty.png";
import img_recommend from "./images/recommend.png";
import img_close from "./images/close.png";
import icon_hot from "images/icon/hot.png";

import { search_key } from "api_xukaiyu/app/content/";
import { searchGoods, searchHistory, recommendList, bookGoods, unBookGoods } from "api_liuhaojie/app/goods";

import util from "commons/util";
let query = util.parseQueryString();

class App extends EntryBase {
    constructor(props) {
        super(props);
        this.state = {
            inputing: false, // 正在输入
            inputText: query.keywords, // 输入内容
            searchText: query.keywords, // 搜索内容
            searchData: [], // 搜索结果
            recommendList: [], // 推荐列表
            search_key: [],
            showScrollLoadText: false,
            page: 1,
            searchHistory: [], // 最近搜索
        }

        this.mainRef = React.createRef();
        this.inputRef = React.createRef();
    }
    componentDidMount() {
        super.componentDidMount();
        // 搜索热词
        search_key().then(res => {
            this.setState({
                search_key: res.data || []
            })
        });
        // 最近搜索
        searchHistory().then(res => {
            this.setState({
                searchHistory: res.data || []
            })
        })
        // 推荐列表
        recommendList().then(res => {
            this.setState({
                recommendList: res.data || []
            })
        })
        if (query.keywords) {
            this.setState({
                inputing: true
            }, () => {
                this.search();
            })
        }
    }
    render() {
        return (
            <Fragment>
                <ScrollReachEndContainer ref={this.mainRef} className={classnames(style.main, "x-scroll-y")} loadText={this.state.scrollLoadText} showScrollLoadText={this.state.showScrollLoadText} onReachEnd={() => {
                    this.reachEnd();
                }}>
                    {
                        !this.state.hasSearch && <div className={style.searchTags}>
                            {
                                this.state.searchHistory.length > 0 && <div className={classnames(style.tagPart, "x-part")}>
                                    <div className={style.tagsTitle}><span>最近搜索</span></div>
                                    <div className={style.tags}>
                                        {
                                            this.state.searchHistory.map((item, index) => {
                                                return (
                                                    <div key={index} className={classnames(style.tegsItem, {
                                                        [style.tegsItemActive]: item.isHot == 1
                                                    })} onClick={() => {
                                                        this.setState({
                                                            searchText: item,
                                                            inputText: item,
                                                            inputing: true
                                                        }, () => {
                                                            this.search();
                                                        })
                                                    }}>
                                                        {
                                                            !!item.isHot && <img src={icon_hot} />
                                                        }
                                                        {item}
                                                    </div>
                                                )
                                            })
                                        }
                                    </div>
                                </div>
                            }
                            <div className={classnames(style.tagPart, "x-part")}>
                                <div className={style.tagsTitle}><span>热门搜索</span></div>
                                <div className={style.tags}>
                                    {
                                        this.state.search_key.map((item, index) => {
                                            return (
                                                <div key={index} className={classnames(style.tegsItem, {
                                                    [style.tegsItemActive]: item.isHot == 1
                                                })} onClick={() => {
                                                    this.setState({
                                                        searchText: item.keywords,
                                                        inputText: item.keywords,
                                                        inputing: true
                                                    }, () => {
                                                        this.search();
                                                    })
                                                }}>
                                                    {
                                                        !!item.isHot && <img src={icon_hot} />
                                                    }
                                                    {item.keywords}
                                                </div>
                                            )
                                        })
                                    }
                                </div>
                            </div>
                        </div>
                    }
                    {
                        // 搜索过，没有搜索数据或者数据长度为0
                        !!this.state.hasSearch && (!this.state.searchData || this.state.searchData.length <= 0) &&
                        <div className={style.empty}>
                            <div className={style.emptyImg}><img src={img_empty} alt="" /></div>
                            <div className={style.emptyText}><span>哎哟，暂时没有相关商品</span></div>
                        </div>
                    }
                    {
                        // 搜索过，有搜索数据并且者数据长度>0
                        !!this.state.hasSearch && this.state.searchData && this.state.searchData.length > 0 &&
                        <div className={style.goodsList}>
                            {
                                this.state.searchData.map((item, index) => {
                                    return (
                                        <CategoryGoodsItem key={item.id} data={item} bookGoods={() => {
                                            bookGoods({
                                                skuId: item.id
                                            }).then(res => {
                                                const newGoodsList = [...this.state.searchData];
                                                newGoodsList[index].isBook = true;
                                                this.setState({
                                                    searchData: newGoodsList
                                                })
                                            })
                                        }} unBookGoods={() => {
                                            unBookGoods({
                                                skuId: item.id
                                            }).then(res => {
                                                const newGoodsList = [...this.state.searchData];
                                                newGoodsList[index].isBook = false;
                                                this.setState({
                                                    searchData: newGoodsList
                                                })
                                            })
                                        }} />
                                    )
                                })
                            }
                        </div>
                    }
                    {
                        // 搜索过，没有索索数据，有推荐数据并且者数据长度>0
                        !!this.state.hasSearch &&
                        (!this.state.searchData || this.state.searchData.length <= 0) &&
                        this.state.recommendList && this.state.recommendList.length > 0 &&
                        <div className={style.recommend}>
                            <div className={style.recommendTitle}>
                                <img src={img_recommend} alt="" />
                            </div>
                            {
                                this.state.recommendList.map((item, index) => {
                                    return (
                                        <CategoryGoodsItem key={item.id} data={item} bookGoods={() => {
                                            bookGoods({
                                                skuId: item.id
                                            }).then(res => {
                                                const newGoodsList = [...this.state.recommendList];
                                                newGoodsList[index].isBook = true;
                                                this.setState({
                                                    recommendList: newGoodsList
                                                })
                                            })
                                        }} unBookGoods={() => {
                                            unBookGoods({
                                                skuId: item.id
                                            }).then(res => {
                                                const newGoodsList = [...this.state.recommendList];
                                                newGoodsList[index].isBook = false;
                                                this.setState({
                                                    recommendList: newGoodsList
                                                })
                                            })
                                        }} />
                                    )
                                })
                            }
                        </div>
                    }
                </ScrollReachEndContainer>
                <div className={style.search}>
                    <div className={classnames(style.searchBar, "wdskeleton-translate")}>
                        <div className={classnames(style.searchBarBg, {
                            [style.hide]: !!this.state.inputing
                        })}><img src={icon_search} />请输入关键字搜索</div>
                        {
                            !!this.state.inputText && !!this.state.inputing && <img className={style.inputClose} src={img_close} alt="" onClick={() => {
                                this.setState({
                                    inputText: "",
                                    hasSearch: false
                                })
                                this.inputRef.current.focus();
                            }} />
                        }
                        <form action="javascript:void(0);">
                            {/* <input type="text" hidden /> */}
                            <input type="search" ref={this.inputRef} value={this.state.inputText} className={style.searchBarInput} onBlur={() => {
                                this.setState({
                                    inputing: !!this.state.inputText
                                })
                            }} onFocus={() => {
                                this.setState({
                                    inputing: true
                                })
                            }} onChange={(e) => {
                                this.setState({
                                    inputText: e.target.value
                                }, () => {
                                    if (this.state.inputing && !this.state.inputText) {
                                        this.setState({
                                            hasSearch: false
                                        })
                                    }
                                })
                            }} onKeyDown={(e) => {
                                // 如果是搜索按钮，并且输入框有值
                                if (e.keyCode == 13 && !!this.state.inputText) {
                                    this.setState({
                                        searchText: this.state.inputText
                                    }, () => {
                                        this.search()
                                    })
                                }

                            }} />
                        </form>
                    </div>
                    <Button className={style.searchBtn} onClick={() => {
                        if (!!this.state.inputText) {
                            this.setState({
                                searchText: this.state.inputText,
                            }, () => {
                                this.search()
                            })
                        }
                    }}>搜索</Button>
                </div>

            </Fragment >
        )
    }

    // 触底
    reachEnd() {
        if (!this.loading && this.state.searchData.length > 0) {
            this.loading = true;
            this.search("loadMore");
        }
    }

    // 搜索
    search(type) {
        // 如果不是加载更多，就是重新搜索，容器滚动回顶部，重置搜索数据和搜索页数
        let page = this.state.page;
        let oldData = this.state.searchData;
        if (type != "loadMore") {
            this.mainRef.current.containerRef.current.scrollTo(0, 0);
            page = 1;
            oldData = [];
        }

        // 搜索请求
        searchGoods({
            word: this.state.searchText,
            page: page
        }).then((res) => {
            const searchData = [...oldData, ...res.data];
            this.setState({
                hasSearch: true,
                searchData: searchData,
                showScrollLoadText: searchData.length > 0,
                scrollLoadText: res.data.length < 10 ? "没有更多商品" : "正在加载更多商品...",
                page: res.data.length < 1 ? page : page + 1
            })
            this.loading = false;
        });
        // console.log(this.state.searchText)

    }
}

export default App;